import JsFileDownload from 'js-file-download'

export function downloadBlob(res) {
  const fileConfig = res.headers.get('content-disposition')
  const regex = /filename\*?=([^']*'')?([^;]*)/
  const filename = decodeURIComponent(regex.exec(fileConfig)[2])
  return res.blob().then((blob) => {
    JsFileDownload(blob, filename, 'application/vnd.ms-excel')
  })
}

export function downloadFile(data, name) {
  const blobData = new Blob([data])
  const url = window.URL.createObjectURL(blobData)
  const a = document.createElement('a')

  a.href = url
  a.download = name
  document.body.appendChild(a)
  a.click()

  setTimeout(() => {
    document.body.removeChild(a) // 防止内存泄漏，将下载链接从页面中移除
    window.URL.revokeObjectURL(url) // 释放 URL 对象的内存
  }, 0)
}
